package top.cn27.luckyhe.mirai.plugin.residence.service;

import org.apache.ibatis.session.SqlSession;
import top.cn27.luckyhe.mirai.plugin.residence.mapper.PlayerListMapper;
import top.cn27.luckyhe.mirai.plugin.residence.pojo.Player;
import top.cn27.luckyhe.mirai.plugin.residence.utils.MyBatisUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PlayerListServiceImpl implements PlayerListService{

    @Override
    public int insertOnePlayer(Player player) throws IOException {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        PlayerListMapper mapper = sqlSession.getMapper(PlayerListMapper.class);

        Player p = selectPlayerByQq(player.getQq());
        if (p != null) {
            mapper.deleteOnePlayer(player.getQq());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("qq", player.getQq());
        map.put("mcId", player.getMcId());
        map.put("checked", player.getChecked());
        map.put("confirmCode", player.getConfirmCode());

        int res = mapper.insertOnePlayer(map);
        sqlSession.commit();
        sqlSession.close();

        return res;
    }

    @Override
    public int deleteOnePlayer(long qq) throws IOException {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        PlayerListMapper mapper = sqlSession.getMapper(PlayerListMapper.class);
        int res = mapper.deleteOnePlayer(qq);
        sqlSession.commit();
        sqlSession.close();

        return res;
    }

    @Override
    public Player selectPlayerByQq(long qq) throws IOException {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        PlayerListMapper mapper = sqlSession.getMapper(PlayerListMapper.class);

        Player player = mapper.selectPlayerByQq(qq);
        sqlSession.close();

        return player;
    }
}
